<?php

namespace app\service;

class FileService
{

    /**
     * 获取指定文件夹，包括子文件夹下的所有文件夹，组装成多维数组
     * @param $root
     * @param $path
     * @return array
     */
    public function getDeepDirs2($root, $path): array
    {

        $fullPath = $root . "/" . $path;

        $files = scandir($path);

        $list = [];
        foreach ($files as $fi){

            if ($fi != "." && $fi != ".."){

                $fp = $fullPath. "/". $fi;
                $up = $path."/".$fi;
                $finfo    = finfo_open(FILEINFO_MIME);
                $mimetype = finfo_file($finfo, $fp);
                finfo_close($finfo);

                if ($mimetype == 'directory'){
                    $li = [
                        'name' => $fi,
                        'mimetype' => $mimetype,
                        'fullPath' => $fp,
                        'urlPath' =>  $up,
                        'type' => 'dir'
                    ];

                    $li['children'] = $this->getDeepDirs2($root, $up);

                    $list[] = $li;

                }

            }
        }

        return $list;

    }


    /**
     * 获取指定文件夹，包括子文件夹下的所有文件，组装成一维数组
     * @param $path
     * @return array
     */
    public function getDeepFiles($root, $path): array
    {

        $fullPath = $root . "/" . $path;

        $files = scandir($fullPath);

        $list = [];
        foreach ($files as $fi){

            if ($fi != "." && $fi != ".."){

                $fp = $fullPath. "/". $fi;
                $up = $path."/".$fi;
                $finfo    = finfo_open(FILEINFO_MIME);
                $mimetype = finfo_file($finfo, $fp);
                if ($mimetype == 'directory'){
//                    $li['type'] = 'dir';

                    $children = $this->getDeepFiles($root, $up);
                    $list = array_merge($list, $children);

                }else{

                    $li = [
                        'name' => $fi,
                        'mimetype' => $mimetype,
                        'fullPath' => $fp,
                        'urlPath' =>  $up
                    ];

                    if (str_starts_with($mimetype, 'image/')){
                        $li['type'] = 'image';
                    }else if (str_starts_with($mimetype, 'video/')){
                        $li['type'] = 'video';
                    }else{
                        $li['type'] = 'file';
                    }

                    $list[] = $li;
                }

            }
        }

        return $list;

    }


}
